package com.ruoyi.merchant.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.merchant.domain.MerchantRegionBinding;
import com.ruoyi.merchant.mapper.MerchantRegionBindingMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.CouponTemplate2;
import com.ruoyi.merchant.domain.MerchantCouponBinding;
import com.ruoyi.merchant.domain.vo.CouponTemplateVO;
import com.ruoyi.merchant.domain.vo.MerchantCouponBindingVO;
import com.ruoyi.merchant.mapper.MerchantCouponBindingMapper;
import com.ruoyi.merchant.mapper.CouponTemplateMapper2;
import com.ruoyi.merchant.service.IMerchantCouponBindingService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;

/**
 * 商家优惠券绑定Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class MerchantCouponBindingServiceImpl implements IMerchantCouponBindingService {
    
    @Autowired
    private MerchantCouponBindingMapper merchantCouponBindingMapper;
    
    @Autowired
    private CouponTemplateMapper2 couponTemplateMapper2;

    @Autowired
    private MerchantRegionBindingMapper merchantRegionBindingMapper;

    /**
     * 查询商家已绑定的优惠券列表
     */
    @Override
    public List<MerchantCouponBindingVO> selectBindingList() {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        List<MerchantCouponBinding> bindings = merchantCouponBindingMapper.selectBindingList(merchantId);
        
        return bindings.stream().map(binding -> {
            MerchantCouponBindingVO vo = new MerchantCouponBindingVO();
            vo.setBindingId(binding.getBindingId());
            vo.setMerchantId(binding.getMerchantId());
            vo.setCouponId(binding.getCouponId());
            vo.setScope(binding.getScope());
            vo.setStatus(binding.getStatus());
            vo.setCreatedAt(binding.getCreateTime());
            
            // 查询优惠券模板信息
            CouponTemplate2 template = couponTemplateMapper2.selectCouponTemplateById(binding.getCouponId());
            if (template != null) {
                vo.setCouponName(template.getName());
                vo.setType(template.getType());
                vo.setTypeName(getTypeName(template.getType()));
                vo.setDiscountValue(template.getDiscountValue());
                vo.setMinOrderAmount(template.getMinOrderAmount());
                vo.setMaxDiscount(template.getMaxDiscount());
                vo.setTotalQuantity(template.getTotalQuantity());
                vo.setUsedQuantity(template.getUsedQuantity());
                vo.setRemainingQuantity(template.getTotalQuantity() - template.getUsedQuantity());
                vo.setValidFrom(template.getValidFrom());
                vo.setValidTo(template.getValidTo());
            }
            
            vo.setScopeName(getScopeName(binding.getScope()));
            vo.setStatusName(getStatusName(binding.getStatus()));
            
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 查询可绑定的平台优惠券模板列表
     */
    @Override
    public List<CouponTemplateVO> selectAvailableTemplates() {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 从商家区域绑定表获取区域ID（取第一个有效绑定的区域）
        Long regionId = null;
        MerchantRegionBinding regionBinding = merchantRegionBindingMapper.selectFirstBindingByMerchantId(merchantId);
        if (regionBinding != null) {
            regionId = regionBinding.getRegionId();
        }
        
        List<CouponTemplate2> templates = merchantCouponBindingMapper.selectAvailableTemplates(merchantId, regionId);
        
        return templates.stream().map(template -> {
            CouponTemplateVO vo = new CouponTemplateVO();
            BeanUtils.copyProperties(template, vo);
            vo.setTypeName(getTypeName(template.getType()));
            vo.setStatusName(getTemplateStatusName(template.getStatus()));
            vo.setRemainingQuantity(template.getTotalQuantity() - template.getUsedQuantity());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 绑定平台优惠券模板
     */
    @Override
    @Transactional
    public int bindTemplate(Long couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 检查是否已绑定
        if (merchantCouponBindingMapper.checkBindingExists(merchantId, couponId) > 0) {
            throw new ServiceException("该优惠券模板已绑定");
        }
        
        // 查询优惠券模板
        CouponTemplate2 template = couponTemplateMapper2.selectCouponTemplateById(couponId);
        if (template == null) {
            throw new ServiceException("优惠券模板不存在");
        }
        
        // 检查模板状态
        if (template.getStatus() != 1) {
            throw new ServiceException("该优惠券模板未启用");
        }
        
        if (template.getAuditStatus() != 1) {
            throw new ServiceException("该优惠券模板未通过审核");
        }

        MerchantCouponBinding deletedBinding =
                merchantCouponBindingMapper.selectDeletedBinding(merchantId, couponId);

        if (deletedBinding != null) {
            // 存在已删除记录 → 恢复
            deletedBinding.setScope(1);
            deletedBinding.setStatus(0);
            return merchantCouponBindingMapper.restoreBinding(deletedBinding);
        } else {
            // 不存在已删除记录 → 新增
            MerchantCouponBinding binding = new MerchantCouponBinding();
            binding.setMerchantId(merchantId);
            binding.setCouponId(couponId);
            binding.setScope(1);
            binding.setStatus(0);
            return merchantCouponBindingMapper.insertBinding(binding);
        }
    }

    /**
     * 启用绑定
     */
    @Override
    @Transactional
    public int enableBinding(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantCouponBinding binding = merchantCouponBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("绑定信息不存在或无权访问");
        }
        
        return merchantCouponBindingMapper.updateBindingStatus(bindingId, merchantId, 0);
    }

    /**
     * 停用绑定
     */
    @Override
    @Transactional
    public int disableBinding(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantCouponBinding binding = merchantCouponBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("绑定信息不存在或无权访问");
        }
        
        return merchantCouponBindingMapper.updateBindingStatus(bindingId, merchantId, 1);
    }

    /**
     * 解除绑定
     */
    @Override
    @Transactional
    public int unbindTemplate(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantCouponBinding binding = merchantCouponBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("绑定信息不存在或无权访问");
        }
        
        return merchantCouponBindingMapper.deleteBinding(bindingId, merchantId);
    }

    /**
     * 获取类型名称
     */
    private String getTypeName(Integer type) {
        switch (type) {
            case 1: return "满减券";
            case 2: return "折扣券";
            case 3: return "代金券";
            default: return "未知";
        }
    }

    /**
     * 获取适用范围名称
     */
    private String getScopeName(Integer scope) {
        switch (scope) {
            case 1: return "商家专属";
            case 2: return "区域共用";
            default: return "未知";
        }
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "启用";
            case 1: return "停用";
            default: return "未知";
        }
    }

    /**
     * 获取模板状态名称
     */
    private String getTemplateStatusName(Integer status) {
        switch (status) {
            case 0: return "未启用";
            case 1: return "启用";
            case 2: return "已过期";
            default: return "未知";
        }
    }
}

